<?php

namespace app\logic\crontab;

use app\model\Shop;
use GuzzleHttp\Client;
use think\facade\Config;

class Token
{
    public function refreshWeimengToken() : void {
        Shop::where([
            'status' => 1,
            'platform_id' => 1
        ])
            ->field('id,params')
            ->select()
            ->each(function ($item) {
                $this->getWeimengToken($item);
            });
    }

    public function getWeimengToken(Shop $shop) : array {
        $query = [
            'grant_type' => 'refresh_token',
            'client_id' => $shop->params->client_id,
            'client_secret' => $shop->params->client_secret,
            'refresh_token' => $shop->params->refresh_token,
        ];
        $url = Config::get('tap.platform.1.token_url');
        $client = new Client();
        $rep = $client->post($url,['query'=>$query,'verify'=>false,'http_errors'=>false])->getBody()->getContents();
        $token = json_decode($rep, true);
        if (isset($token['error_description'])) {
            return error($token['error_description']);
        }
        $shop->params->access_token = $token['access_token'];
        $shop->save();
        return success('获取成功', $token['access_token']);
    }

}
